package zuochengyun;

import list.LinkedListCreate;
import list.ListNode;

public class ReverseApartNode {

	public static void main(String[] args) {
		int[] array = {5, 8, 4, 6, 2, 7};
		ListNode head = LinkedListCreate.createList(array);
		ListNode newList = reverse(head, 1, 4);
		LinkedListCreate.printList(newList);
	}
	
	public static ListNode reverse(ListNode head, int from, int to) {
		ListNode fromPre = null, toNext = null;
		int length = 0;
		ListNode temp = head;
		//找到from的前一个结点和to的后一个结点，注意这两个可能都是null
		while (temp != null) {
			length++;
			fromPre = (length == from - 1 ? temp : fromPre);
			toNext = (length == to + 1 ? temp : toNext);
			temp = temp.next;
		}
		//无效输入判断
		if (from > to || from < 1 || to > length) {
			throw new IllegalArgumentException("wrong arg");
		}
		if(fromPre != null && toNext != null){
			System.out.println("next value : " + toNext.val + " pre value: " + fromPre.val);
		}
		//如果fromPre为null，说明第一个要交换的是head，否则是fromPre.next
		temp = (fromPre == null ? head : fromPre.next);

		//再找到from结点的前一个结点和to结点的后一个结点之后
		//要首先将from指向toNext,因为之后这个from这个结点是反转的最后一个结点了，我们没有持有它的饮用
		ListNode temp2 = temp.next;
		temp.next = toNext;
		ListNode pre = temp, next = null;
		temp = temp2;
		while (temp != toNext) {
			next = temp.next;
			temp.next = pre;
			pre = temp;
			temp = next;
		}
		//head没有发生改变
		if (fromPre != null) { 
			fromPre.next = pre;
			return head;
		}
		return pre;

	}

}
